<template>
  <div class="logistics-management">
    <h2 class="page-title">物流管理</h2>

    <el-row gutter="20" class="dashboard-summary" style="margin-bottom: 20px">
      <el-col :span="6" v-for="item in logisticsSummary" :key="item.value">
        <el-card
            class="summary-card"
            :style="{ background: `linear-gradient(to right, ${item.color}, #ffffff)` }"
            @click="filterByStatus(item.value)"
        >
          <div class="summary-icon">{{ item.icon }}</div>
          <div class="summary-title">{{ item.label }}</div>
          <div class="summary-value">{{ item.count }}</div>
        </el-card>
      </el-col>
    </el-row>

    <div class="filter-bar">
      <el-row :gutter="20" align="middle">
        <el-col :span="10">
          <el-input
              v-model="filterKeyword"
              placeholder="搜索订单号 / 商品名 / 买家"
              prefix-icon="Search"
              clearable
          />
        </el-col>
        <el-col :span="6">
          <el-select v-model="filterStatus" placeholder="按物流状态筛选" clearable style="width:100%">
            <el-option
                v-for="opt in STATUS_OPTIONS"
                :key="opt.value"
                :label="opt.label"
                :value="opt.value"
            />
          </el-select>
        </el-col>
      </el-row>
    </div>

    <!-- 已发货订单列表 -->
    <el-card class="management-card">
      <el-row justify="space-between" style="margin-bottom: 12px">
        <el-col>
          <el-button
              type="primary"
              :disabled="selectedOrders.length === 0"
              @click="openBatchStatusDialog"
          >
            批量更新物流状态
          </el-button>
          <el-button type="success" @click="exportOrdersCSV">
            导出发货记录
          </el-button>
        </el-col>
      </el-row>
      <el-table
          :data="shippedOrders"
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="orderId" label="订单号" width="120" />
        <el-table-column prop="productName" label="商品名称" />
        <el-table-column prop="buyerName" label="买家" />
        <el-table-column prop="createdAt" label="发货时间" />
<!--        <el-table-column prop="logisticsStatus" label="物流状态" />-->
        <!-- 列表里物流状态列 -->
        <el-table-column prop="logisticsStatus" label="物流状态">
          <template #default="scope">
            <!-- 已填写：用中文；未填写：灰色标签 -->
            <el-tag v-if="scope.row.hasLogisticsInfo"
                    type="info"
                    effect="plain">
              {{ STATUS_TEXT[scope.row.logisticsStatus] }}
            </el-tag>
            <span v-else style="color:#bbb">未填写</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <div class="action-buttons">
              <el-button type="primary" size="small" @click="openLogisticsDialog(scope.row)">
                物流管理
              </el-button>
              <el-button type="info" size="small" @click="viewLogisticsTimeline(scope.row)">
                查看进度
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!--      <p v-else class="empty-text">暂无已发货订单</p>-->
    </el-card>

    <!-- 物流管理弹窗（填写/更新物流信息） -->
    <el-dialog
        v-model="showDialog"
        title="物流信息管理"
        width="460px"
        :close-on-click-modal="false"
    >
      <div class="form-group">
        <label>物流公司：</label>
        <div v-if="!selectedOrder.hasLogisticsInfo">
          <el-input
              v-model="logisticsForm.logisticsCompany"
              placeholder="请输入物流公司"
          />
        </div>
        <div v-else class="readonly-text">
          {{ logisticsForm.logisticsCompany }}
        </div>
      </div>

      <div class="form-group">
        <label>物流单号：</label>
        <div v-if="!selectedOrder.hasLogisticsInfo">
          <el-input
              v-model="logisticsForm.logisticsNo"
              placeholder="请输入物流单号"
          />
        </div>
        <div v-else class="readonly-text">
          {{ logisticsForm.logisticsNo }}
        </div>
      </div>

      <div class="form-group">
        <label>物流状态：</label>
        <!-- ② 下拉框改用 filteredStatusOptions -->
        <el-select v-model.number="logisticsForm.logisticsStatus"
                   placeholder="请选择状态"
                   style="width:100%">
          <el-option
              v-for="opt in filteredStatusOptions"
              :key="opt.value"
              :label="opt.label"
              :value="opt.value" />
        </el-select>
      </div>

      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="submitLogistics">提交</el-button>
      </template>
    </el-dialog>

    <!-- 查看物流时间线弹窗 -->
    <el-dialog
        v-model="showTimelineDialog"
        title="物流进度"
        width="400px"
        :close-on-click-modal="false"
    >
      <el-timeline>
        <el-timeline-item
            v-for="(step, index) in timelineSteps"
            :key="index"
            :timestamp="step.time"
            :color="index === timelineSteps.length - 1 ? 'green' : 'blue'"
        >
          {{ step.label }}
        </el-timeline-item>
      </el-timeline>

      <template #footer>
        <el-button @click="showTimelineDialog = false">关闭</el-button>
      </template>
    </el-dialog>
    <el-dialog
        v-model="showBatchDialog"
        title="批量更新物流状态"
        width="400px"
    >
      <el-select v-model="batchStatus" placeholder="选择新状态" style="width:100%">
        <el-option
            v-for="opt in STATUS_OPTIONS"
            :key="opt.value"
            :label="opt.label"
            :value="opt.value"
        />
      </el-select>

      <template #footer>
        <el-button @click="showBatchDialog = false">取消</el-button>
        <el-button type="primary" @click="submitBatchStatus">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import request from "@/utils/request.js";

export default {
  setup() {
    const STATUS_OPTIONS = [
      { value: 0, label: '商品准备中' },
      { value: 1, label: '已发货' },
      { value: 2, label: '已揽件' },
      { value: 3, label: '运输中' },
      { value: 4, label: '派件中' },
      { value: 5, label: '待取件' }
    ]

// 数字 → 中文快速查表
    const STATUS_TEXT = STATUS_OPTIONS.reduce((m, o) => {
      m[o.value] = o.label
      return m
    }, {})

    /* ① 计算属性：根据当前行的旧状态过滤选项 */
    const filteredStatusOptions = computed(() => {
      if (!selectedOrder.value) return STATUS_OPTIONS;
      const cur = selectedOrder.value.logisticsStatus ?? 0;
      return STATUS_OPTIONS.filter(opt => opt.value >= cur);
    });

    // 所有订单数据
    const orders = ref([])

    // 弹窗状态
    const showDialog = ref(false)
    const showTimelineDialog = ref(false)

    // 当前选中的订单
    const selectedOrder = ref(null)
    const selectedOrders = ref([])
    const handleSelectionChange = (val) => {
      selectedOrders.value = val
    }
    const showBatchDialog = ref(false)
    const batchStatus = ref('')

    const openBatchStatusDialog = () => {
      batchStatus.value = ''
      showBatchDialog.value = true
    }

    const submitBatchStatus = () => {
      const newStatus = Number(batchStatus.value)

      const needAdd = []
      const needUpdate = []

      selectedOrders.value.forEach(row => {
        if (!row.hasLogisticsInfo) {
          needAdd.push(row.orderId)
        } else {
          if (row.logisticsStatus > newStatus) {
            return ElMessage.warning(`订单 ${row.orderId} 只能向后更新物流状态`)
          }
          needUpdate.push({ id: row.logisticsId, logisticsStatus: row.logisticsStatus })
        }
      })

      if (needAdd.length) {
        return ElMessage.warning('所选订单中有尚未填写物流信息的记录，请先逐条录入物流后再批量更新')
      }

      if (!needUpdate.length) return

      request.post(`/logistics/update?logisticsStatus=${newStatus}`, needUpdate)
          .then(res => {
            if (res.code === '200') {
              ElMessage.success('批量更新成功')
              showBatchDialog.value = false
              fetchOrders()
            } else if (res.code === '406') {
              ElMessage.warning('只能向后更新物流状态')
            } else {
              ElMessage.error(res.msg || '批量更新失败')
            }
          })
          .catch(() => {
            ElMessage.error('批量更新失败，请稍后重试')
          })
    }
    // 物流表单
    const logisticsForm = reactive({
      logisticsCompany: '',
      logisticsNo: '',
      logisticsStatus: ''
    })

    // 用于时间线展示
    const timelineSteps = ref([])

    // 全部可选状态
    const allStatusOptions = [
      '商品准备中',
      '已发货',
      '已揽件',
      '运输中',
      '派件中',
      '待取件'
    ]

    const filterKeyword = ref('')
    const filterStatus = ref('')
    const filterByStatus = (statusValue) => {
      filterStatus.value  = statusValue          // 0-5 或 'unfilled'
      filterKeyword.value = ''                   // 清空关键词
      setTimeout(() => {
        document.querySelector('.logistics-table-wrapper')
            ?.scrollIntoView({ behavior: 'smooth' })
      }, 100)
    }

    const shippedOrders = computed(() => {
      const kw   = filterKeyword.value.trim()
      const stat = filterStatus.value

      return orders.value.filter(o => {
        const hitKw =
            !kw ||
            o.orderId.toString().includes(kw) ||
            o.productName.includes(kw) ||
            o.buyerName.includes(kw)

        const hitStat =
            stat === '' || stat === null || stat === undefined
                ? true
                : (stat === 'unfilled'
                    ? !o.hasLogisticsInfo
                    : o.logisticsStatus === stat)

        return hitKw && hitStat
      })
    })

    const logisticsSummary = computed(() => {
      // 统计六种状态 + 未填写
      const countMap = { unfilled: 0 }
      STATUS_OPTIONS.forEach(opt => (countMap[opt.value] = 0))

      orders.value.forEach(o => {
        if (o.hasLogisticsInfo) {
          countMap[o.logisticsStatus]++
        } else {
          countMap.unfilled++
        }
      })

      const colorMap = {
        0: '#4facfe', 1: '#43e97b', 2: '#f093fb',
        3: '#f5576c', 4: '#ff9966', 5: '#5ee7df',
        unfilled: '#bbb'
      }

      const iconMap = {
        0: '📦', 1: '🚚', 2: '📬',
        3: '🚛', 4: '🏃‍♂️', 5: '📮',
        unfilled: '❓'
      }

      const cards = STATUS_OPTIONS.map(opt => ({
        value: opt.value,      // 记录 value 供点击筛选
        label: opt.label,
        count: countMap[opt.value],
        color: colorMap[opt.value],
        icon:  iconMap[opt.value]
      }))

      cards.push({
        value: 'unfilled',
        label: '未填写',
        count: countMap.unfilled,
        color: colorMap.unfilled,
        icon:  iconMap.unfilled
      })

      return cards
    })

    const fetchOrders = () => {
      request.get('/order/selectOrders', {
        params: { pageNum: 1, pageSize: 100 }
      })
          .then(res => {
            console.log('[原始响应]', res)
            if (res.code !== '200') throw new Error(res.msg || '获取失败')

            orders.value = res.data.map(o => ({
              orderId:        o.id,
              orderItemsId:   o.id,
              productName:    o.productName,
              buyerName:      o.buyerName,
              createdAt:      o.createdAt,
              totalPrice:     o.totalPrice,
              confirmation:   o.confirmation,
              stockUp:        o.stockUp,
              sendOrder:      o.sendOrder,
              logisticsStatus: '',
              logisticsCompany: '',
              logisticsNo: '',
              hasLogisticsInfo: false
            }))
            console.log('%c[DEBUG] orders 初始数组 →', 'color:green', orders.value.map(o => ({
              orderId: o.orderId,
              id: o.id
            })))

            orders.value.forEach(fetchLogisticsInfo)
          })
          .catch(err => {
            console.error(err)
            ElMessage.error(err.message)
          })
    }

    const fetchLogisticsInfo = (order) => {
      request.get(`/logistics/getlogistics/${order.orderId}`)
          .then(res => {
            console.log('物流查询结果:', res)
            if (res.code === '200' && res.data) {
              order.logisticsId = res.data.id
              order.logisticsStatus = res.data.logisticsStatus
              order.logisticsCompany = res.data.logisticsCompany
              order.logisticsNo = res.data.logisticsNo
              order.hasLogisticsInfo = true
            } else {
              order.logisticsStatus = ''
              order.logisticsCompany = ''
              order.logisticsNo = ''
              order.hasLogisticsInfo = false
            }
          })
          .catch(err => {
            console.error('获取物流失败', err)
          })
    }

    // 点击“物流管理”按钮
    const openLogisticsDialog = (order) => {
      selectedOrder.value = order
      if (order.hasLogisticsInfo) {
        // 只允许更新状态
        logisticsForm.logisticsCompany = order.logisticsCompany
        logisticsForm.logisticsNo = order.logisticsNo
        logisticsForm.logisticsStatus =
            order.logisticsStatus || '商品准备中'
      } else {
        // 第一次填写
        logisticsForm.logisticsCompany = ''
        logisticsForm.logisticsNo = ''
        // logisticsForm.logisticsStatus = '商品准备中'
        logisticsForm.logisticsStatus = 0            // 用数字 0
      }
      showDialog.value = true
    }

    const submitLogistics = () => {
      const order = selectedOrder.value
      if (!order) return

      if (!order.hasLogisticsInfo) {
        const payload = {
          orderItemsId: order.orderItemsId,
          logisticsCompany: logisticsForm.logisticsCompany,
          logisticsNo: logisticsForm.logisticsNo,
          logisticsStatus: Number(logisticsForm.logisticsStatus)
        }
        request.post('/logistics/add', payload)
            .then(afterSubmit)
      } else {
        const newStatus = Number(logisticsForm.logisticsStatus)
        const list = [{
          id: order.logisticsId,
          logisticsStatus: order.logisticsStatus
        }]
        request.post(`/logistics/update?logisticsStatus=${newStatus}`, list)
            .then(afterSubmit)
      }

      function afterSubmit(res) {
        if (res.code === '200') {
          ElMessage.success('物流信息已保存')
          showDialog.value = false
          fetchOrders()
        } else if (res.code === '406') {
          ElMessage.warning('只能向后更新物流状态')
        } else {
          ElMessage.error(res.msg || '提交失败')
        }
      }
    }

    const viewLogisticsTimeline = (order) => {
      selectedOrder.value = order
      request.get(`/logistics/getlogistics/${order.orderId}`)
          .then(res => {
            if (res.code === '200' && res.data) {
              timelineSteps.value = buildTimelineSteps(res.data.logisticsStatus)
            } else {
              timelineSteps.value = []
            }
            showTimelineDialog.value = true
          })
          .catch(err => {
            console.error(err)
            ElMessage.error('获取物流信息失败')
          })
    }
    const buildTimelineSteps = (currentStatusNumber) => {
      const allStates = STATUS_OPTIONS.map(o => o.value);   // [0,1,2,3,4,5]
      const idx = allStates.indexOf(currentStatusNumber);
      if (idx === -1) return [];

      const reached = allStates.slice(0, idx + 1);
      const now = new Date();

      return reached.map((num, i) => ({
        label: STATUS_TEXT[num],                            // 中文
        time : new Date(
            now.getTime() - (reached.length - 1 - i) * 3600 * 1000
        ).toLocaleString()
      }));
    };
    const exportOrdersCSV = () => {
      if (shippedOrders.value.length === 0) {
        ElMessage.warning('暂无发货记录可导出')
        return
      }

      const headers = ['订单号', '商品名称', '买家', '发货时间', '物流状态']
      const rows = shippedOrders.value.map(order => [
        // order.id,
        order.orderId,
        order.productName,
        order.buyerName,
        order.createdAt,
        order.logisticsStatus || '未填写'
      ])

      const csvContent = [headers, ...rows]
          .map(row => row.map(item => `"${String(item).replace(/"/g, '""')}"`).join(','))
          .join('\n')

      const blob = new Blob([`\uFEFF${csvContent}`], { type: 'text/csv;charset=utf-8;' }) // 带 BOM 解决中文乱码
      const url = URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.setAttribute('download', `发货记录_${new Date().toISOString().slice(0,10)}.csv`)
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    }


    onMounted(() => {
      fetchOrders()
    })

    return {
      STATUS_OPTIONS,
      STATUS_TEXT,
      filteredStatusOptions,
      orders,
      shippedOrders,
      logisticsSummary,
      showDialog,
      showTimelineDialog,
      selectedOrder,
      logisticsForm,
      timelineSteps,
      allStatusOptions,
      filterKeyword,
      filterStatus,
      selectedOrders,
      handleSelectionChange,
      showBatchDialog,
      batchStatus,
      openBatchStatusDialog,
      submitBatchStatus,
      fetchOrders,
      openLogisticsDialog,
      submitLogistics,
      viewLogisticsTimeline,
      filterByStatus,
      exportOrdersCSV
    }
  }
}
</script>

<style scoped>
/* 1. 整体布局美化 */
.logistics-management {
  padding: 20px;
  background: #f9fafb;
  min-height: 100vh;
}

.management-card {
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  border-radius: 8px;
  background: #fff;
  border: none;
}

/* 2. 表格样式 */
.logistics-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 10px;
  border-radius: 5px;
  overflow: hidden;
}

.logistics-table thead {
  background: #f3f4f6;
}

.logistics-table th,
.logistics-table td {
  padding: 12px;
  text-align: center;
}

.table-row:nth-child(even) {
  background-color: #fafafa;
}

/* 3. 空数据提示 */
.empty-text {
  text-align: center;
  color: #999;
  font-size: 14px;
  margin: 10px 0;
}

/* 4. 弹窗内容美化 */
.form-group {
  margin-bottom: 16px;
}
.form-group label {
  display: block;
  font-weight: 600;
  margin-bottom: 4px;
}
.readonly-text {
  padding: 6px 8px;
  background: #f0f0f0;
  border-radius: 4px;
}

/* 5. 按钮容器 */
.action-cell > * {
  margin: 0 4px 4px 0;
}
.action-buttons {
  display: flex;
  gap: 6px;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
}


/* 6. modal overlay & content (Element Plus默认有，但这里可再自定义) */
.modal {
  position: fixed;
  top: 0; left: 0;
  width: 100vw; height: 100vh;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
}
.summary-card {
  text-align: center;
  padding: 20px 10px;
  border-radius: 12px;
  color: #333;
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;
  animation: fadeInUp 0.4s ease;
}

.summary-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
}

.summary-icon {
  font-size: 32px;
  margin-bottom: 10px;
}

.summary-title {
  font-size: 14px;
  color: #555;
  margin-bottom: 4px;
}

.summary-value {
  font-size: 26px;
  font-weight: 700;
  color: #222;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
.filter-bar {
  background: #ffffff;
  padding: 16px 20px;
  border-radius: 12px;
  margin-bottom: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.04);
  animation: fadeInDown 0.3s ease;
}

.el-input__inner,
.el-select .el-input__inner {
  border-radius: 8px !important;
  transition: all 0.3s;
}

.el-input__inner:focus,
.el-select .el-input__inner:focus {
  box-shadow: 0 0 0 2px #4facfe22;
}
@keyframes fadeInDown {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
.el-table {
  border-radius: 8px;
  overflow: hidden;
  background: #fff;
  box-shadow: 0 2px 10px rgba(0,0,0,0.05);
}

.el-table th {
  background: #f8f9fb !important;
  font-weight: 600;
  color: #555;
}

.el-table td {
  font-size: 14px;
  color: #333;
  background-color: #fff;
  transition: background 0.3s;
}

.el-table__row:hover td {
  background: #f6faff;
}

.el-table .el-button {
  margin-right: 6px;
}
.dashboard-summary {
  display: flex;
  flex-wrap: nowrap;
  overflow-x: auto;
  gap: 16px;
  margin-bottom: 20px;
  padding-bottom: 4px;
}
.summary-card {
  flex: 0 0 180px;
  cursor: pointer;
  user-select: none;
  transition: all 0.2s ease;
}
.summary-card:hover {
  transform: translateY(-3px) scale(1.03);
}
</style>
